package com.xgr.wonderful.activity;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.BitmapUtils;
import com.xgr.wonderful.utils.CacheUtils;
import com.xgr.wonderful.utils.HXUtils;
import com.xgr.wonderful.utils.LocalLikeRelationsUtils;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.view.CircleImageView;
import com.xgr.wonderful.activity.base.BaseActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.Photo;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.MainActivity;
import com.xgr.wonderful.R;

public class UploadAvatarActivity extends BaseActivity {

	private Button mUploadAvatarBtn;
	private CircleImageView myAvatar = null;
	private TextView mUsernameTv;
	private TextView mUseridTv;
	private ActionBar mActionBar ;

	private User localUser;
	
	private String targetFilePath  ;
	
	private HttpProxy httpProxy ;
	
	private boolean withImg =false ;
	@Override
	protected void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		setContentView(R.layout.activity_uploadavatar);
		mUploadAvatarBtn = (Button) findViewById(R.id.uploadavatar_Btn);
		mUsernameTv = (TextView) findViewById(R.id.uploadavatar_usernameTv);
		mUseridTv = (TextView) findViewById(R.id.uploadavatar_useridTv);
		myAvatar = (CircleImageView) findViewById(R.id.upload_myavatar);
		mActionBar = (ActionBar) findViewById(R.id.actionbar_uploadavatar) ;
		
		mActionBar.setTitle("头像");
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				finish() ;
			}		
			@Override
			public int getDrawable() {
				return R.drawable.weix_logo_blank;
			}
		}) ;
		httpProxy = new HttpProxy() ;
		localUser = LocalUserUtils.getInstance().getLocalUser() ;
		mUseridTv.setText(localUser!= null? ""+ localUser.getID(): "0000");
		mUsernameTv.setText(localUser!= null ? ""+localUser.getUsername():"没有登录");
		if (localUser!= null && localUser.getPhoto()!= null && localUser.getPhoto().getSmall()!= null){
			ImageLoader.getInstance().displayImage(
					localUser.getPhoto().getSmall(), 
					myAvatar) ;
		}
		mUploadAvatarBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				if (!withImg){
					ToastFactory.getToast(mContext, "请选择头像").show() ;
					return;
				}
				doUploadAvatar(getImgFile());
			}
		});
		

		LinearLayout mAvatarLayout = (LinearLayout) findViewById(R.id.upload_myavatar_layout);
		mAvatarLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					break;
				case MotionEvent.ACTION_UP:
					BitmapUtils.showGetImgeDialog((Activity) mContext, getImgFile()) ;
					break;
				default:
					break;
				}
				return true;// 只有down事件返回为true的时候，才能监听到UP
			}
		});
	}
	
	/**
	 * 得到存放 照片的文件,固定在avatar.jpg 
	 * @return
	 */
	private File  getImgFile (){
		File  f = new File(CacheUtils.getCacheDirectory(mContext, 
				true, "image")+
				File.separator +
				"pic_"+"avatar"+".jpg") ;
		if (! f.exists()){
			try {
				f.createNewFile() ;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return f  ;
	}
	
	/**
	 * 流程应该是:
	 * 先从album得到图片uri,zoom后保存到getImageFile中，再将file根据filepath压缩
	 * 成bitmap后读取到内存中，再将bitmap压缩成file(可设置file大小)，然后可以上传 file 
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK){
			switch (requestCode) {
			case BitmapUtils.CAMERA_REQUEST:
				File f = getImgFile() ;
				if (f.exists() && f.length()>0){
					Uri uri = Uri.fromFile(f) ;
					BitmapUtils.startImageZoom(this, uri, uri,
							1000, 1000, 1, 1) ;
				}
				break;
			case BitmapUtils.ALBUM_REQUESRT:
				if (data == null){
					return ;
				}
				BitmapUtils.startImageZoom(this, data.getData(),
						Uri.fromFile(getImgFile()), 1000, 1000, 1, 1) ;
				break ;
			case BitmapUtils.CROPED_REQUEST:
				Bitmap bitmap = BitmapUtils.compressBitmapFromFile(
						getImgFile().getAbsolutePath() ) ;
				if (bitmap != null){
					targetFilePath = BitmapUtils.compressBmpAndSaveToFile(mContext,
							bitmap, getImgFile().getName(), 80) ;
					myAvatar.setImageBitmap(bitmap) ;
					withImg = true ;
				}
				break ;
			default:
				break;
			}
		}
	}
	/**
	 * 这个方法只在L以下的版本中才可以，所以不再使用
	 * @return
	 */
	private boolean checkAvatar(){
		if (myAvatar.getDrawable().getConstantState()==
				mResources.getDrawable(R.drawable.user_icon_default).getConstantState()){
			return false;
		}
		return true;
	}
	
	private void doUploadAvatar(File file)
	{
		httpProxy.uploadFile(file , new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				// TODO Auto-generated method stub
				Photo photo = null;
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
					try {
						photo = new Gson().fromJson(result, Photo.class);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (photo!= null && photo.getSmall()!= null){
						ToastFactory.getToast(mContext, "上传头像成功").show() ;
						doUpdateUser(photo) ;
					}
				} else {	
					LogUtils.i(TAG, "photo upload fial") ;
					cancelProgressDialog() ;
					ToastFactory.getToast(mContext, "上传头像失败").show() ;
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				showProgressDialog("正在上传头像...", false) ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				cancelProgressDialog() ;
				ToastFactory.getToast(mContext, "上传头像失败，请检查网络环境后重试").show() ;
			}
		});
	}
	
	private void doUpdateUser(final Photo photo)
	{
		User user = new User(localUser.getID(),null,
				null, photo, null) ;
		httpProxy.updateUser(new Gson().toJson(user), new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				// TODO Auto-generated method stub
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
					ToastFactory.getToast(mContext, "头像更新成功").show() ;
					sputil.setLogin(true);
					LocalLikeRelationsUtils.getInstance().buildLikeRelations(
							mContext);
					//保存头像信息
					User tempUser = LocalUserUtils.getInstance().getLocalUser() ;
					tempUser.setPhoto(photo) ;
					LocalUserUtils.getInstance().saveLocalUser(mContext, tempUser) ;
					
					DatabaseUtil.getInstance().initConversationDao(mContext) ;
					HXUtils.EMLogin(LocalUserUtils.getInstance().getLocalUserID().toString(),
							LocalUserUtils.getInstance().getLocalUserID().toString());
					redictToActivity(mContext, MainActivity.class, null);
				} else {
					cancelProgressDialog();
					LogUtils.i(TAG, "fail");
					ToastFactory.getToast(mContext, "更新用户头像失败").show();
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				showProgressDialog("正在更新用户信息...", false);
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				cancelProgressDialog();
				LogUtils.i(TAG, "fail info:"+info);
				ToastFactory.getToast(mContext, "更新用户头像失败").show();
			}
		});
	}
}
